package com.yld.car.market;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.yld.car.db.RecentlyViewedDBHelper;

import com.yld.car.application.MyApplication;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.ImageUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.domain.DetailInfoCar;
import com.yld.car.domain.EditCarInfo;
import com.yld.car.domain.UserInfo;

/**
 * svn update
 * 
 * @author apple
 * 
 */
public class CarDetailInfoActivity extends BaseActivity implements
		OnItemClickListener, OnClickListener {

	private String id;

	private String carName;
	private String carSeries;
	private MyApplication application;

	private ProgressBar mBar;

	// 车源所属状态
	private boolean isMySelf;

	private String price;

	// 经销商dealerid
	private String dealerid;

	boolean isCurrentDealer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		application = this.mApp;
		// 自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.car_detail);
		utils = NetworkProgressUtils.getInstance();

		// 设置布局
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		mBar = (ProgressBar) findViewById(R.id.progressBar);
		Intent i = getIntent();
		isMySelf = i.getBooleanExtra("isMyself", false);
		dealerid = i.getStringExtra("dealerid");
		Button localButton = (Button) findViewById(R.id.rightButton);
		showButton();
		btn1 = (Button) findViewById(R.id.itemBtn1);
		btn2 = (Button) findViewById(R.id.itemBtn2);
		btn3 = (Button) findViewById(R.id.itemBtn3);

		UserInfo u = (UserInfo) readObject("userInfo");
		String currentDealerId = u.getUserId();
		isCurrentDealer = currentDealerId.equals(dealerid);
		System.out.println(isCurrentDealer + ",,,,");
		if (isMySelf || isCurrentDealer) {
			localButton.setText("编辑");
			localButton.setOnClickListener(editClickListener);
			btn1.setOnClickListener(btn1MySelfClickListener);
			btn1.setBackgroundResource(R.drawable.selector_btn_reflush);
			btn2.setOnClickListener(btn2MySelfClickListener);
			btn2.setBackgroundResource(R.drawable.selector_btn_del);
			btn3.setOnClickListener(btn3MySelfClickListener);
			btn3.setBackgroundResource(R.drawable.selector_btn_share);
		} else {
			localButton.setText("分享");
			localButton.setOnClickListener(this);

			btn1.setOnClickListener(btn1ClickListener);

			btn2.setOnClickListener(btn2ClickListener);

			btn3.setOnClickListener(btn3ClickListener);

		}

		localButton.setVisibility(View.VISIBLE);
		id = i.getStringExtra("cId");
		carName = i.getStringExtra("carName");
		carType = i.getStringExtra("carType");

		carSeries = i.getStringExtra("carSeries");
		price = i.getStringExtra("price");
		TextView titleText = ((TextView) findViewById(R.id.title));

		titleText.setText("车源详情");
		listView = (ListView) findViewById(R.id.list1);
		listView.setOnItemClickListener(this);

		HashMap<String, String> title = new HashMap<String, String>();
		title.put("title", "title");
		title.put("carName", "宝马");
		title.put("standardPrice", "指导价");

		allTypes.add(title);
		HashMap<String, String> price = new HashMap<String, String>();

		price.put("title", "price");
		price.put("price", "价格¥");
		allTypes.add(price);

		HashMap<String, String> color = new HashMap<String, String>();

		color.put("title", "color");
		color.put("color", "颜色");

		allTypes.add(color);
		HashMap<String, String> type = new HashMap<String, String>();
		type.put("title", "type");
		type.put("type", "类型");

		allTypes.add(type);

		// 选配配置和车架号

		HashMap<String, String> addDate = new HashMap<String, String>();
		addDate.put("title", "addDate");
		addDate.put("addDate", "发布日期");

		allTypes.add(addDate);

		HashMap<String, String> publisher = new HashMap<String, String>();
		publisher.put("title", "publisher");
		publisher.put("publisher", "发布者");

		allTypes.add(publisher);
		HashMap<String, String> configurate = new HashMap<String, String>();
		configurate.put("title", "configurate");
		configurate.put("configurate", "配置");
		allTypes.add(configurate);

		HashMap<String, String> vin = new HashMap<String, String>();
		vin.put("title", "vin");
		vin.put("vin", "车架号");
		allTypes.add(vin);

		HashMap<String, String> sellArea = new HashMap<String, String>();
		sellArea.put("title", "sellArea");
		sellArea.put("sellArea", "销售区域");

		allTypes.add(sellArea);
		HashMap<String, String> img = new HashMap<String, String>();
		img.put("title", "img");
		img.put("img", "图片");

		allTypes.add(img);
	}

	ListView listView = null;

	private View.OnClickListener editClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			// Toast.makeText(CarDetailInfoActivity.this, "编辑功有正在完善",
			// Toast.LENGTH_SHORT).show();
			mApp.setUpdateConfigState(false);
			Intent intent = new Intent();
			intent.setClass(CarDetailInfoActivity.this,
					MyCarUpdatePublishActivity.class);
			// 传一个状态，表示当前为车辆信息的编辑状态
			// intent.putExtra("isEditor", true);

			// 传入当前详细信息
			// intent.putExtra("detailInfo", mDetailInfoCar);
			mApp.setEditor(false);
			intent.putExtra("carType", carName);
			intent.putExtra("carSeries", carSeries);
			intent.putExtra("price", price);
			intent.putExtra("id", id);
			startActivity(intent);

		}
	};
	// 车辆详情要显示的所有信息
	private ArrayList<Map<String, String>> allTypes = new ArrayList<Map<String, String>>();

	private DetailInfoCar mDetailInfoCar;

	private void showButton() {

		Button localButton = (Button) findViewById(R.id.leftButton);
		localButton.setVisibility(View.VISIBLE);

		localButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();

			}
		});
	}

	private NetworkProgressUtils utils;

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		new CarDetailInfoTask().execute("");
	}

	private class CarDetailInfoTask extends
			AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {

			allBitmaps.clear();
			allImageUrls.clear();
			// System.out.println("id===>" + id);
			HashMap<String, String> allParams = new HashMap<String, String>();
			allParams.put("cId", id);
			// 添加当前登录用户的id
			UserInfo u = (UserInfo) readObject("userInfo");
			allParams.put("userId", u.getUserId());
			Object o = utils.getWebservicesByData(
					ConstantUtils.NAME_SPACE,
					ConstantUtils.ALL_METHROD_NAME.get(7),
					ConstantUtils.NAME_SPACE
							+ ConstantUtils.ALL_METHROD_NAME.get(7),
					ConstantUtils.GET_CAR_INFO_BY_CAR_ID_URL, allParams);

			// .out.println(o);

			// System.out.println("-----------------");
			ArrayList<Car> all = utils.parseJson(o.toString(), "table",
					NetworkProgressUtils.DETAIL_INFO_CAR_TYPE, false);

			// 缓存编辑车的详细信息对象

			new Thread(new Runnable() {

				@Override
				public void run() {
					HashMap<String, String> allParams = new HashMap<String, String>();
					allParams.put("carId", id);

					Object o = utils.getWebservicesByData(
							ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(47),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME.get(47),
							ConstantUtils.GET_CAR_BY_EDIT_ID_URL, allParams);

					//System.out.println("cache---->"+o);
					EditCarInfo e = utils.parseEditCarInfo(o.toString());

					//System.out.println("$$$$$$" + e);
					mApp.setmEditCarInfo(e);
				}
			}).start();

			publishProgress("");
			// for (Car car : all) {
			//
			// if (car instanceof DetailInfoCar) {
			//
			// DetailInfoCar d = (DetailInfoCar) car;
			// System.out
			// .println(d.getDealerid() + "img====" + d.getImg());
			// }
			// }

			if (all.size() > 0) {
				Car c = all.get(0);
				if (c instanceof DetailInfoCar) {

					final DetailInfoCar d = (DetailInfoCar) c;

					mDetailInfoCar = d;
					String img = d.getImg();

					final String[] imgUrls = img.split(";");
					// ;
					System.out.println("img=====>" + img);
					// if (imgUrls.length >= 1) {
					for (int i = 0; i < imgUrls.length; i++) {

						System.out.println("donwloadUrl==" + imgUrls[i]);
						final String name = imgUrls[i];
						final Bitmap bitmap = utils.downloadImage(name);
						if (bitmap != null) {

							allBitmaps.add(bitmap);
							allImageUrls.add(name);
							// System.out.println("name==" + name);
							final String name1 = name.substring(
									name.lastIndexOf("/") + 1, name.length());
							// System.out.println("name1===" + name1);
							new Thread(new Runnable() {

								@Override
								public void run() {
									File localFile = new File(
											PublishCarPickPhotoActivity.IMG_CACHE_PATH);
									if (!localFile.exists())
										localFile.mkdirs();
									try {

										FileOutputStream fos = new FileOutputStream(
												new File(localFile, name1));
										fos.write(ImageUtils
												.bitmapToByte(bitmap));
										fos.flush();
										fos.close();
									} catch (FileNotFoundException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
							}).start();
						}
					}
					// }

					// new Thread(new Runnable() {
					//
					// /**
					// * { "recordcount":"1", --返回的数据条数 "table": [ { "no":"1",
					// * --序列ID "id": "1683", --车辆ID "name": "外白内黑棕",
					// * --车辆外饰内饰简称，即这辆车的标题 "press": "115", --价格（单位W）
					// * "qhtime": "2014-04-30", --期货到港时间（现货为空） "adddate":
					// * "2014-04-11 18:19:33", --这辆车的录入时间 "companyname": "",
					// * --这辆车所属经销商公司名称 "xppz": "运动包¤扩展真皮内饰¤红卡钳", --选配配置
					// * "vin": "", --就是车架号 "img": "", --车辆图片 "dealerid":
					// * "183" --所属经销商ID } …… ] }
					// */
					//
					// @Override
					// public void run() {
					// SQLiteDatabase sqLiteDatabase = mApp.getmDbHelper()
					// .getWritableDatabase();
					// ContentValues values = new ContentValues();
					// values.put(RecentlyViewedDBHelper.ID, d.getId());
					// values.put(RecentlyViewedDBHelper.NO, d.getNo());
					// values.put(RecentlyViewedDBHelper.NAME, d.getName());
					// values.put(RecentlyViewedDBHelper.PRESS,
					// d.getPress());
					// values.put(RecentlyViewedDBHelper.QHTIME,
					// d.getQhtime());
					// values.put(RecentlyViewedDBHelper.ADD_DATE,
					// d.getAdddate());
					// values.put(RecentlyViewedDBHelper.COMPANY_NAME,
					// d.getCompanyname());
					// values.put(RecentlyViewedDBHelper.XPPZ, d.getXppz());
					//
					// values.put(RecentlyViewedDBHelper.VIN, d.getVin());
					// values.put(RecentlyViewedDBHelper.DEALER_ID,
					// d.getDealerid());
					//
					// if (imgUrls != null && imgUrls.length >= 3
					// && allBitmaps.size() > 0) {
					//
					// String imageName1 = imgUrls[0];
					// imageName1 = imageName1.substring(
					// imageName1.lastIndexOf("/") + 1,
					// imageName1.length());
					// String imageName2 = imgUrls[1];
					// imageName2 = imageName2.substring(
					// imageName2.lastIndexOf("/") + 1,
					// imageName2.length());
					// String imageName3 = imgUrls[2];
					// imageName3 = imageName3.substring(
					// imageName3.lastIndexOf("/") + 1,
					// imageName3.length());
					// values.put(
					// RecentlyViewedDBHelper.IMAGE1_PATH,
					// PublishCarPickPhotoActivity.IMG_CACHE_PATH
					// + imageName1);
					//
					// values.put(
					// RecentlyViewedDBHelper.IMAGE2_PATH,
					// PublishCarPickPhotoActivity.IMG_CACHE_PATH
					// + imageName2);
					// values.put(
					// RecentlyViewedDBHelper.IMAGE3_PATH,
					// PublishCarPickPhotoActivity.IMG_CACHE_PATH
					// + imageName3);
					// }
					//
					// long rowId = sqLiteDatabase
					// .insert(RecentlyViewedDBHelper.RECENT_VIEW_DETAIL_TABLE,
					// null, values);
					// if (rowId > 0) {
					// System.out.println("Detail:insert------>插入成功。");
					// } else {
					//
					// System.out.println("Detail:insert------>插入失败。");
					// }
					//
					// }
					// }).start();
					// 清空集合
					// application.getAllBitmaps().clear();
					application.setAllBitmaps(allBitmaps);
					// 清空集合
					// application.getAllImageUrls().clear();
					application.setAllImageUrls(allImageUrls);
					// System.out.println(d.getDealerid() + "=====img====" +
					// d.getImg());
				}
			}
			return all;
		}

		@Override
		protected void onProgressUpdate(String... values) {

			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {

			mBar.setVisibility(View.VISIBLE);
			listView.setVisibility(View.GONE);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			mBar.setVisibility(View.GONE);
			listView.setVisibility(View.VISIBLE);
			if (result != null && result.size() > 0) {
				DetailInfoCar d = (DetailInfoCar) result.get(0);
				DetailCarAdapter adapter = new DetailCarAdapter(d);

				String attentionState = d.getGuanzu();
				telNumber = d.getTelephone();
				if (!isMySelf && !isCurrentDealer) {
					if ("0".equals(attentionState)) {
						btn3.setBackgroundResource(R.drawable.selector_car_detail_action_attention_car);
						isAttention = false;

					} else {
						btn3.setBackgroundResource(R.drawable.selector_car_detail_action_cancel_attention_car);
						isAttention = true;
					}
				} else {
					btn3.setBackgroundResource(R.drawable.selector_btn_share);
				}

				listView.setAdapter(adapter);
			}

		}

	}

	private ArrayList<String> allImageUrls = new ArrayList<String>();
	private ArrayList<Bitmap> allBitmaps = new ArrayList<Bitmap>();
	private String carType;

	private class DetailCarAdapter extends BaseAdapter {

		private DetailInfoCar car;

		public DetailCarAdapter(DetailInfoCar car) {
			this.car = car;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return allTypes.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return allTypes.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// ImageView imageView = new ImageView(getApplicationContext());
			// imageView.setLayoutParams(new LinearLayout.LayoutParams(
			// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			// imageView.setImageBitmap(allBitmaps.get(position));

			Map<String, String> hashMap = allTypes.get(position);

			String s = hashMap.get("title");

			if ("title".equals(s)) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_title, null);
				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(car.getName());
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemTitle2);
				tv1.setVisibility(View.VISIBLE);
				tv1.setText("指导价:" + car.getPress() + "万");
			}
			if ("price".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);

				tv.setText(hashMap.get("price"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setTextColor(Color.RED);
				tv1.setText(car.getPress() + "万");

			}
			if ("color".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				// tv.setTextColor(Color.RED);
				tv.setText(hashMap.get("color"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				String colorName = car.getWsname() + "/" + car.getNsname();
				tv1.setText(colorName);
			}
			if ("type".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("type"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);

				// System.out.println("..." + car.getXhorgh());

				String l_car_type = carType;
				//System.out.println(l_car_type);
				if (l_car_type != null && l_car_type.indexOf("现货") >= 0||l_car_type!=null&&l_car_type.indexOf("到港")>=0) {

				}
				else {
					l_car_type = l_car_type + "-" + car.getQhtime() + "-到港";
				}
				boolean isEditor = mApp.isEditor();
				//System.out.println(l_car_type+"isEditor--->"+isEditor);
				if (isEditor) {
					int type = mApp.getmCarStateValue();
					if (type == 0) {
						l_car_type = "现货";
					} else if (type == 1) {
						l_car_type = "期货-" + car.getQhtime() + "-到港";
					}
				}
				// if (carType == null || carType.equals("")) {
				// //carType = "美国-期货";
				//
				// }

				tv1.setText(l_car_type);
			}
			if ("addDate".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("addDate"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setText("" + car.getAdddate());
			}
			if ("publisher".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_publisher, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("publisher"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setText("" + car.getCompanyname());
			}
			if ("configurate".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("configurate"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setText("" + car.getXppz());
			}

			if ("vin".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("vin"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setText("" + car.getVin());
			}
			if ("sellArea".equals(s)) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_other, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("sellArea"));
				TextView tv1 = (TextView) convertView
						.findViewById(R.id.itemContent);
				tv1.setText("全国");
			}

			if ("img".equals(s)) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_detail_items_pic, null);

				TextView tv = (TextView) convertView
						.findViewById(R.id.itemTitle);
				tv.setText(hashMap.get("img"));
				ImageView imageView = (ImageView) convertView
						.findViewById(R.id.itemPic1);
				ImageView imageView1 = (ImageView) convertView
						.findViewById(R.id.itemPic2);
				ImageView imageView2 = (ImageView) convertView
						.findViewById(R.id.itemPic3);
				ImageView imageView3=(ImageView) convertView.findViewById(R.id.itemPic4);
				
				if (allBitmaps.size() == 4) {

					imageView.setImageBitmap(allBitmaps.get(0));

					imageView1.setImageBitmap(allBitmaps.get(1));

					imageView2.setImageBitmap(allBitmaps.get(2));
					imageView3.setImageBitmap(allBitmaps.get(3));
				}
				else if (allBitmaps.size() == 3) {

					imageView.setImageBitmap(allBitmaps.get(0));

					imageView1.setImageBitmap(allBitmaps.get(1));

					imageView2.setImageBitmap(allBitmaps.get(2));
				} else if (allBitmaps.size() == 2) {
					imageView.setImageBitmap(allBitmaps.get(0));

					imageView1.setImageBitmap(allBitmaps.get(1));
				} else if (allBitmaps.size() == 1) {
					imageView.setImageBitmap(allBitmaps.get(0));
				}

				// System.out.println("guanzu--->"+car.getGuanzu());
				// return convertView;

			}

			return convertView;
		}

		@Override
		public boolean isEnabled(int position) {

			Map<String, String> hashMap = allTypes.get(position);

			String s = hashMap.get("title");
			if ("img".equals(s) || "publisher".equals(s)) {
				return super.isEnabled(position);
			}
			return false;
			// return super.isEnabled(position);
		}

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		Map<String, String> hashMap = allTypes.get(position);

		String s = hashMap.get("title");

		if ("img".equals(s)) {

			Intent intent = new Intent();
			intent.setClass(this, PhotoLargeActivity.class);
			startActivity(intent);
		}

		if ("publisher".equals(s)) {

			if (mDetailInfoCar != null) {
				Intent intent = new Intent();
				intent.setClass(this, DealerMarketActivity.class);
				intent.putExtra("bId", mDetailInfoCar.getDealerid());
				StringBuffer sb = new StringBuffer();
				// 品牌型号、价格、外内饰简称、状态、配置 就5个东西
				sb.append("来自爱车行分享，您家的这款车源：" + carName + "/" + carSeries + "/"
						+ mDetailInfoCar.getPress() + "万/"
						+ mDetailInfoCar.getName() + "/" + carType + "/"
						+ mDetailInfoCar.getXppz());
				intent.putExtra("shareSms", sb.toString());
				startActivity(intent);
			}

		}
	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		switch (id) {
		case R.id.rightButton:// 分享功能
			progressShareBtn();
			break;

		default:
			break;
		}

	}

	// 分享功能
	private void progressShareBtn() {

		if (mDetailInfoCar != null) {

			StringBuffer sb = new StringBuffer();
			// 品牌型号、价格、外内饰简称、状态、配置 就5个东西
			sb.append("来自爱车行分享，您家的这款车源：" + carName + "/" + carSeries + "/"
					+ mDetailInfoCar.getPress() + "万/"
					+ mDetailInfoCar.getName() + "/" + carType + "/"
					+ mDetailInfoCar.getXppz());
			Intent intent = new Intent();

			intent.setClass(this, CarInfoShareWayActivity.class);
			intent.putExtra("smsText", sb.toString());
			intent.putExtra("imageUrl", mDetailInfoCar.getImg());
			startActivity(intent);
		} else {
			Toast.makeText(this, "暂时无法使用分享功能", Toast.LENGTH_SHORT).show();
		}
	}

	private Button btn1;
	private Button btn2;
	private Button btn3;

	private View.OnClickListener btn1MySelfClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// telDo();

			new Thread(new Runnable() {

				@Override
				public void run() {

					refreshOrDeleteCarInfo(WHAT_REFRESH_INDEX,
							ConstantUtils.GET_BATCH_REFRESH_BY_CAR_ID_URL);

				}
			}).start();

		}
	};

	private View.OnClickListener btn2MySelfClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			new Thread(new Runnable() {

				@Override
				public void run() {

					refreshOrDeleteCarInfo(WHAT_DELETE_INDEX,
							ConstantUtils.DELETE_CAR_BY_CAR_ID_URL);

				}
			}).start();
		}
	};
	private View.OnClickListener btn3MySelfClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			progressShareBtn();
		}
	};

	private View.OnClickListener btn1ClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			telDo();

		}
	};

	private View.OnClickListener btn2ClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			shareToMessage();
		}
	};
	private View.OnClickListener btn3ClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			final String fromDealersId = ((UserInfo) readObject("userInfo"))
					.getUserId();

			if (isAttention) {

				new Thread(new Runnable() {

					@Override
					public void run() {

						progressAttentionCarBtn(fromDealersId, id, 40,
								ConstantUtils.CANCEL_ATTENTION_TO_CAR_URL);

					}
				}).start();

			} else {

				new Thread(new Runnable() {

					@Override
					public void run() {

						progressAttentionCarBtn(fromDealersId, id, 39,
								ConstantUtils.ATTENTION_TO_CAR_URL);

					}
				}).start();

			}

		}
	};

	private String telNumber = "15823912195";

	/**
	 * 分享短信
	 */
	private void shareToMessage() {
		// UserInfo u = (UserInfo) readObject("userInfo");
		// telNumber = u.getUserphone();
		if (telNumber == null) {
			telNumber = "15823912195";
		}
		if (mDetailInfoCar != null) {
			StringBuffer sb = new StringBuffer();
			// 品牌型号、价格、外内饰简称、状态、配置 就5个东西
			sb.append("来自爱车行分享，您家的这款车源：" + carName + "/" + carSeries + "/"
					+ mDetailInfoCar.getPress() + "万/"
					+ mDetailInfoCar.getName() + "/" + carType + "/"
					+ mDetailInfoCar.getXppz());
			Intent localIntent = new Intent("android.intent.action.SENDTO",
					Uri.parse("smsto:" + telNumber));
			localIntent.putExtra("sms_body", sb.toString());
			startActivity(localIntent);
			finish();
		} else {
			Toast.makeText(this, "暂时无法完成短信分享", Toast.LENGTH_SHORT).show();
		}

	}

	private void telDo() {
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
		localBuilder.setTitle("拨打电话");
		// UserInfo u = (UserInfo) readObject("userInfo");
		// telNumber = u.getUserphone();
		if (telNumber == null) {
			telNumber = "15823912195";
		}
		localBuilder.setMessage(telNumber);
		localBuilder.setCancelable(false);
		localBuilder.setPositiveButton("呼叫",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {
						Intent localIntent = new Intent(
								"android.intent.action.CALL", Uri.parse("tel:"
										+ telNumber));
						startActivity(localIntent);
					}
				});
		localBuilder.setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {
					}
				});
		localBuilder.create().show();
	}

	// 描述当前是否关注的状态
	private boolean isAttention;

	private void progressAttentionCarBtn(String fromDealersId, String carId,
			int methodIndex, String methodURL) {
		HashMap<String, String> allParams = new HashMap<String, String>();

		allParams.put("fromDealersId", fromDealersId);
		allParams.put("carId", carId);

		Object o = utils.getWebservicesByData(
				ConstantUtils.NAME_SPACE,
				ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				ConstantUtils.NAME_SPACE
						+ ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				methodURL, allParams);

		Message msg = mHandler.obtainMessage();
		msg.obj = o;
		msg.what = methodIndex;
		mHandler.sendMessage(msg);
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			String targetMsg = msg.obj.toString();
			int what = msg.what;
			boolean isFinish = false;
			String alertMsg = "";
			switch (what) {
			case WHAT_INDEX_ONE:
				alertMsg = "关注该车成功";
				isAttention = true;
				// if (!isMySelf) {
				btn3.setBackgroundResource(R.drawable.selector_car_detail_action_cancel_attention_car);
				// }

				break;

			case WHAT_INDEX_TWO:
				alertMsg = "成功取消关注此车";

				btn3.setBackgroundResource(R.drawable.selector_car_detail_action_attention_car);
				isAttention = false;
				break;
			case WHAT_REFRESH_INDEX:
				alertMsg = "刷新成功";
				break;
			case WHAT_DELETE_INDEX:
				alertMsg = "删除成功";
				isFinish = true;
				break;
			}

			if (targetMsg != null
					&& (targetMsg.indexOf("操作成功") >= 0 || targetMsg
							.indexOf("刷新成功") >= 0)) {

				Toast.makeText(CarDetailInfoActivity.this, alertMsg,
						Toast.LENGTH_SHORT).show();

				if (isFinish) {
					finish();
				}
			} else {
				Toast.makeText(CarDetailInfoActivity.this, "操作失败，请稍候再试",
						Toast.LENGTH_SHORT).show();
			}
		}

	};
	public static final int WHAT_INDEX_ONE = 39;
	public static final int WHAT_INDEX_TWO = 40;
	// 定义刷新和删除功能请求的what标记
	public static final int WHAT_REFRESH_INDEX = 41;
	public static final int WHAT_DELETE_INDEX = 42;

	// 底部刷新或者删除功能
	private void refreshOrDeleteCarInfo(int methodIndex, String methodURL) {

		HashMap<String, String> allParams = new HashMap<String, String>();

		allParams.put("carId", id);

		Object o = utils.getWebservicesByData(
				ConstantUtils.NAME_SPACE,
				ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				ConstantUtils.NAME_SPACE
						+ ConstantUtils.ALL_METHROD_NAME.get(methodIndex),
				methodURL, allParams);

		Message msg = mHandler.obtainMessage();
		msg.obj = o;
		msg.what = methodIndex;
		mHandler.sendMessage(msg);
	}

}
